Ext.override(Deppon.config.Dpap, {
  statics: {
    RESOURCE_PATH: 'ext-dpap',
  }
});
Ext.override(Deppon.config.Foss, {
  statics: {
    //静态资源地址
    RESOURCE_PATH: Deppon.config.Dpap.RESOURCE_PATH,
  }
});
function setWithCrosIsFalse(){
  Ext.override(Ext.data.Connection, {
    useDefaultXhrHeader: false,
    cors: false,
    withCredentials: false
  });

}

/** 跨域登录参数 */
Ext.override(Ext.data.Connection, {
  setOptions: function (options, scope) {
    //兼容FOSS Token
    if(IF_FOSS_ECS_WMC_SWITCH){

      //ECS超时弥补
      if(options.url.indexOf(ECS_SERVER_NAME)>=0){
        options.urlParams = Ext.applyIf(options.urlParams || {}, userInfo.params);
        options.urlParams = Ext.applyIf(options.urlParams || {}, userInfo.fossParams);
        return this.callParent([options, scope]);
      }

      //开关打开状态  全部走UUMS  TOKEN
      options.urlParams = Ext.applyIf(options.urlParams || {}, userInfo.params);
      return this.callParent([options, scope]);
    } else {
      //开关关闭状态  ECS/FOSS/WMC 拼装模拟TOOKEN
      //ECS
      if(options.url.indexOf(ECS_SERVER_NAME)>=0) {
        setWithCrosIsFalse();
        options.urlParams = Ext.applyIf(options.urlParams || {}, userInfo.fossParams);
        return this.callParent([options, scope]);
      }
      //FOSS
      else if(options.url.indexOf(FOSS_SERVER_NAME)>=0){
        if (window.browser.startsWith('Firefox')) {
          // 请使用谷歌浏览器， 下载地址为http://google.com
          // Ext.MessageBox.hide();
          document.querySelector('#recommendedBrowser').style.display = 'block';
          return;
        } else {
          Ext.override(Ext.data.Connection, {
            useDefaultXhrHeader: false,
            cors: true,
            withCredentials: true
          });
          options.urlParams = Ext.applyIf(options.urlParams || {}, userInfo.fossParams);
          return this.callParent([options, scope]);
        }
      }
      //WMC
      else if(options.url.indexOf(WMC_SERVER_NAME)>=0){
        setWithCrosIsFalse();
        options.urlParams = Ext.applyIf(options.urlParams || {}, userInfo.fossParams);
        return this.callParent([options, scope]);
      } else {
        //其他系统走UUMS  TOKEN
        setWithCrosIsFalse();
        options.urlParams = Ext.applyIf(options.urlParams || {}, userInfo.params);
        return this.callParent([options, scope]);
      }
    }

  }
});



/**
 * 重写EXTJS 4.1中的conection类中onComplete方法，使架构异常得到解决 同时记录异常信息
 * 重写onUploadComplete解决跨域文件上传时候可以以JSON返回结果
 */
Ext.override(Ext.data.Connection, {
  isFormUpload: function (options) {
    var result = this.callParent([options]);
    if (result) {
      top.window.uploadState = 0;
    }
    return result;
  },
  onJsonResponse: function (contentType, response, options) {
    if (contentType && contentType.toLowerCase() == 'application/json;charset=utf-8') {
      var json = Ext.decode(response.responseText);
      if (json) {
        //业务执行成功
        if (json.success && !json.isException) {
          Ext.callback(options.success, options.scope, [response, options]);
          //业务异常
        } else if (!json.success && !json.isException) {
          Ext.callback(options.exception, options.scope, [response, options]);
          //未知异常
        } else if (!json.success && json.isException) {
          if (json.stackTrace && json.stackTrace.indexOf("UserNotLoginException") > 0) {
            Deppon.errorMessage.Box.showGoLoginWin();
            return;
          }
          if (json.errorCode == Deppon.config.Dpap.USER_NOTALLOW) {
            Ext.ux.Toast.msg('', json.message, 'error');
          } else {
            var ErrorMessageWindow = Ext.create('Deppon.errorMessage.Window', {
              message: json.message,
              stackTrace: json.stackTrace
            });
            ErrorMessageWindow.show();
          }
          Ext.callback(options.unknownException, options.scope, [response, options]);
        }
      }
    } else {
      if (response.responseText != null) {
        if (response.responseText.indexOf('<meta content="LOGIN_JSP">') > 0) {
          Deppon.errorMessage.Box.showGoLoginWin();
          return;
        }
      }
      Ext.callback(options.success, options.scope, [response, options]);
    }
  },
  onUploadComplete: function (frame, options) {
    var me = this,
      response = {
        responseText: '',
        responseXML: null
      }, contentType, doc, firstChild,
      flag = false;
    try {
      if (top.window.uploadState == 1) {
        response.responseText = frame.contentWindow.name;
        flag = true;
        Ext.callback(options.success, options.scope, [response, options]);
      } else {
        doc = frame.contentWindow.document || frame.contentDocument || window.frames[frame.id].document;
        if (doc) {
          if (doc.body) {
            //更新textarea为pre
            if (/pre/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in pre
              response.responseText = firstChild.innerHTML;
              contentType = 'application/json;charset=utf-8';
            } else {
              response.responseText = doc.body.innerHTML;
              contentType = 'text/html'
            }
          }
          response.responseXML = doc.XMLDocument || doc;
          me.onJsonResponse(contentType, response, options);
          flag = true;
        }
      }
    } catch (e) {
      if (top.window.uploadState == 0) {
        top.window.uploadState += 1;
        frame.contentWindow.location = UAP_SERVER_NAME + 'empty.html';
        Ext.fly(frame).on('load', Ext.Function.bind(this.onUploadComplete, this, [frame, options]), null, {single: true});
        return;
      } else {
        console.error(e);
      }
    }
    me.fireEvent('requestcomplete', me, response, options);
    if (!flag) {
      Ext.callback(options.callback, options.scope, [options, true, response]);
    }
    setTimeout(function () {
      Ext.removeNode(frame);
    }, 100);
  },
  onComplete: function (request) {
    var me = this,
      options = request.options,
      result, success, response;
    try {
      result = me.parseStatus(request.xhr.status);
    } catch (e) {
      result = {
        success: false,
        isException: false
      };
    }
    success = result.success;
    if (success) {
      response = me.createResponse(request);
      me.fireEvent('requestcomplete', me, response, options);
      me.onJsonResponse(response.getResponseHeader('Content-Type'), response, options);
    } else {
      if (result.isException || request.aborted || request.timedout) {
        response = me.createException(request);
      } else {
        response = me.createResponse(request);
      }
      me.fireEvent('requestexception', me, response, options);
      Ext.callback(options.failure, options.scope, [response, options]);
      //记录异常
      if (options.url.startsWith(currentUumsFunction.functionUrl)) {
        var exceptionDetail = "status:" + response.status + ",statusText:" + response.statusText;
        statisticsMenuException(currentUumsFunction,exceptionDetail);
      }

      //  Ext.MessageBox.hide();
      //服务端异常提示
      Ext.MessageBox.show({
        title: Deppon.errorMessage.Box.title,
        msg: Deppon.errorMessage.Box.msg,
        buttons: Ext.MessageBox.OK,
        icon: Ext.MessageBox.ERROR
      });
    }
    Ext.callback(options.callback, options.scope, [options, success, response]);
    delete me.requests[request.id];
    return response;
  },
});

/**
 * 修改Controller 的control方法
 */
Ext.override(Ext.app.Controller.prototype,{
  control:function(selectors){
    this.initEven = selectors;
  }
});

/**
 * 修改Application 对Controller 的onLaunch方法之前执行一段方法
 */
Ext.override(Ext.app.Application.prototype,{
  onBeforeLaunch:function(){
    var me = this,
      controllers, c, cLen, controller;

    if (me.enableQuickTips) {
      Ext.tip.QuickTipManager.init();
    }

    if (me.autoCreateViewport) {
      me.getView('Viewport').create();
    }

    me.launch.call(this.scope || this);
    me.launched = true;
    me.fireEvent('launch', this);

    controllers = me.controllers.items;
    cLen        = controllers.length;

    for (c = 0; c < cLen; c++) {
      controller = controllers[c];

      /********添加代码 开始********************************/
      var initEven = controller.initEven;
      if(initEven){
        for(var selector in initEven){
          var component = Ext.ComponentQuery.query(selector);
          if(component&&component.length>0){
            var evenObj = initEven[selector];
            for(var evenName in evenObj){
              if(component[0].hasListener(evenName)){
                component[0].mun(component[0],evenName);
              }
              component[0].mon(component[0],evenName,evenObj[evenName],controller);
            }
            //evenObj.scope = controller;
            //component[0].on(evenObj);
          }
        }
      }
      /********添加代码 结束********************************/
      controller.onLaunch(this);
    }
  }
});


/** 指定Extjs中占位图片的路径，代替Data URI Scheme */
Ext.BLANK_IMAGE_URL = Deppon.config.Foss.RESOURCE_PATH + '/images/default/tree/s.gif';

/**
 * 重写 新建tab功能
 * @param tID 待打开的tab id
 * @param tText tab显示文本值
 * @param tLoc tab页面请求的URL
 * @param params 请求的参数
 * @param loadTabFun 加载panel的function
 * @param uapExtOpt Uap扩展参数(统计菜单性能)
 */
function addTab(tID, tText, tLoc, params, loadTabFun, uapExtOpt) {
  var tabPanel = Ext.getCmp('mainAreaPanel'), tab = Ext.getCmp(tID);
  if (params != "" && params != null) {
    tabPanel.params = params;
  }

  /** 设置菜单打开上限个数,排除首页 **/
  if (tabPanel.items.length > 20) {
    Ext.Msg.alert("友情提示", "您不能打开更多的菜单 !");
    return;
  }

  // 判断是打开Tab还是切换Tab
  if (!tab) {
    if (uapExtOpt) {
      menuAccessPathLog(uapExtOpt.uumsFunction.functionCode, uapExtOpt.uumsFunction.functionName, uapExtOpt.accessPath,uapExtOpt.uumsFunction.sourceSystem);
    }
    var beginTime = new Date().getTime(); // 打开Tab开始时间
    tabPanel.add({
      id: tID,
      title: tText,
      layout: 'fit',
      closable: true,
      enableTabScroll: false,
      tabConfig: {width: 160},
      cls: 'autoHeight',
      bodyCls: 'autoHeight',
      renderer:function(){
        metadata.attr = "title=" + tText;
        return value;
      },
      loader: {
        scripts: true,
        autoLoad: true,
        params: params,
        url: tLoc,
        listeners: {
          load: function (loader, response, options, eOpts) {
            if (loadTabFun != null) {
              loadTabFun(loader.getTarget(), options.params);
            }
          }
        }
      },
      listeners: {
        afterrender: function () {
          this.tab.btnInnerEl.dom.title = tText;
          if (uapExtOpt) {
            uapExtOpt.submitOpenTabTime(beginTime); // 提交打开Tab页时间
          }
        }
      }
    });

    tabPanel.setActiveTab(tabPanel.child('#' + tID));
  } else {
    tabPanel.setActiveTab(tab);
    if (loadTabFun != null) {
      loadTabFun(tab, params);
    }
  }
};

/**
 * 重写 新建iframe功能
 * @param tID 待打开的tab id
 * @param tText tab显示文本值
 * @param tLoc tab页面请求的URL
 * @param params 请求的参数
 * @param loadTabFun 加载panel的function
 * @param uapExtOpt Uap扩展参数(统计菜单性能)
 */
function addIframe(tID, tText, tLoc, params, loadTabFun, uapExtOpt) {
  var tabPanel = Ext.getCmp('mainAreaPanel'), tab = Ext.getCmp(tID);
  if (params != "" && params != null) {
    tabPanel.params = params;
  }

  /** 设置菜单打开上限个数,排除首页 **/
  if (tabPanel.items.length > 20) {
    Ext.Msg.alert("友情提示", "您不能打开更多的菜单 !");
    return;
  }

  // 判断是打开Tab还是切换Tab
  if (!tab) {
    if (uapExtOpt) {
      menuAccessPathLog(uapExtOpt.uumsFunction.functionCode, uapExtOpt.uumsFunction.functionName, uapExtOpt.accessPath,uapExtOpt.uumsFunction.sourceSystem);
    }
    // 打开iframe开始时间
    var beginTime = new Date().getTime();
    var iframeID = tID + '-iframe';
    var iframeHtml = '<iframe class="iframe-uap" id="{0}" scrolling="no"></iframe>'.replace('{0}', iframeID);
    tabPanel.add({
      id: tID,
      title: tText,
      layout: 'fit',
      closable: true,
      tabConfig: {width: 160},
      cls: 'autoHeight',
      bodyCls: 'autoHeight',
      html: iframeHtml,
      listeners: {
        afterrender: function () {
          this.tab.btnInnerEl.dom.title = tText;
          var iframe = Ext.getElementById(iframeID);
          iframe.onload = function () {
            if (uapExtOpt) {
              // 提交加载iframe页时间
              uapExtOpt.submitOpenTabTime(beginTime);
            }
            var getStyle = function(obj,attr){    //获取非行间样式，obj是对象，attr是值
              if(obj){
                if(obj.currentStyle){   //针对ie获取非行间样式
                  return obj.currentStyle[attr];
                }else{
                  return getComputedStyle(obj,false)[attr];   //针对非ie
                }
              }

            };
            var domBody =  iframe.contentDocument.body;
            var outerHeightBody = Number(getStyle(domBody,'height'))+
              Number(getStyle(domBody,'border'))+
              Number(getStyle(domBody,'padding'));
            iframe.style.height = outerHeightBody+'px';
          };
          iframe.src = tLoc;
        }
      }
    });
    tabPanel.setActiveTab(tabPanel.child('#' + tID));
  } else {
    tabPanel.setActiveTab(tab);
    if (loadTabFun != null) {
      loadTabFun(tab, params);
    }
  }

}

/**
 * 展示TAB页
 * @param title 标题
 * @param href URL
 * @param viewType 展示方式
 * @param params 请求参数
 * @param uapExtOpt Uap扩展参数（统计菜单性能和使用率）
 */
var currentUumsFunction;

function viewTab(title, href, viewType, params, uapExtOpt) {

  if (uapExtOpt) {
    //记录当前菜单信息
    currentUumsFunction = uapExtOpt.uumsFunction;
  } else if (href) {
    currentUumsFunction = {"functionUrl": href};
  }

  if (typeof(viewType) == 'undefined') {
    // 不传参模糊判断iframe还是div
    viewType = 'DIV';
  }

  // 添加给周边系统用以判断使用什么JS
  href = Ext.urlAppend(href, 'isUap=true');

  // 当时iframe或者div时的TAB_ID和地址设置
  if (viewType.toUpperCase() == 'IFRAME') {
    var md = forge.md.md5.create();
    md.update(href);
    addIframe(md.digest().toHex(), title, href, params, null, uapExtOpt);
  } else if (viewType.toUpperCase() == 'DIV') {
    var hrefArr = href.split("/");
    if (hrefArr.length < 5) {
      Ext.ux.Toast.msg('提示',
        '菜单URL配置不符合规则,请联系系统管理员', 'error', 3000);
      return;
    }
    var tID = 'T_', tLoc = href, href = "";
    for (var i = 4; i < hrefArr.length; i++) {
      href += "/" + hrefArr[i];
    }
    for (var h = 1; h < href.length; h++) {
      if (href.charAt(h) != '/') {
        tID = tID + href.charAt(h);
      } else {
        tID = tID + '-';
      }
    }
    tID = tID.substring(0, tID.lastIndexOf('?'));
    if (tID.indexOf('.') != -1) {
      tID = tID.substring(0, tID.lastIndexOf('.'));
    }
    addTab(tID, title, tLoc, params, null, uapExtOpt);
  }
}


/**
 * 关闭页签
 * @param href URL请求地址
 * @param viewType 请求类型
 */
function closeTab(href, viewType) {
  //关闭页签
  var tabPanel = Ext.getCmp('mainAreaPanel');
  var tab = getTabById(href, viewType);
  if (tabPanel && tab) {
    tabPanel.remove(tab);
  }
}

/**
 * 获取TAB对象
 *  @param href URL请求地址
 * @param viewType 请求类型
 */
function getTabById(href, viewType) {

  if (typeof(viewType) == 'undefined') {
    // 不传参模糊判断iframe还是div
    viewType = 'DIV';
  }

  //TAB id
  var tID;

  if (viewType.toUpperCase() == "IFRAME") {
    var md = forge.md.md5.create();
    md.update(href);
    tID = md.digest().toHex();
  } else if (viewType.toUpperCase() == "DIV") {
    var hrefArr = href.split("/");
    if (hrefArr.length < 5) {
      Ext.ux.Toast.msg('提示',
        '菜单URL配置不符合规则,请联系系统管理员', 'error', 3000);
      return;
    }
    tID = 'T_';
    var tLoc = href, href = "";
    for (var i = 4; i < hrefArr.length; i++) {
      href += "/" + hrefArr[i];
    }
    for (var h = 1; h < href.length; h++) {
      if (href.charAt(h) != '/') {
        tID = tID + href.charAt(h);
      } else {
        tID = tID + '-';
      }
    }
    if (tID.indexOf('.') != -1) {
      tID = tID.substring(0, tID.lastIndexOf('.'));
    } else {
      tID = tID.substring(0, tID.lastIndexOf('?'));
    }
  }

  return tab = Ext.getCmp(tID);
}

//定义一个标签页
Ext.define('Dpap.main.TabPanel', {
  extend: 'Ext.tab.Panel',
  id: "mainAreaPanel",
  width: '100%',
  columnWidth: 1,
  plain: true,
  cls: 'autoWidth',
  bodyCls: "tabFrame",
  componentCls: "mainArea",
  tabCls: 'tab-menu',
  params: null,
  //右手overflow下拉插件
  plugins: [{
    ptype: 'tabscrollermenu',
    id: 'OFB_menu',
    maxText: 40,
    pageSize: 100
  }, {
    ptype: 'tabclosemenu',
    closeTabText: '关闭',
    closeOthersTabsText: '关闭其他',
    closeAllTabsText: '关闭所有'
  }],
  initListeners: function () {
    var me = this;
    me.listeners = {
      //关闭前清内存里相应项目
      beforeremove: function (panel, tab) {
        //清理组件
        var tabId = tab.id,
          conId = tabId + '_content',
          toolbarId = tabId + '_toolbar';
        //判断是否存在tab的主页面，如果不存在就无需清理
        if (Ext.getCmp(conId) == null) {
          return;
        }
        //清空ComponentManager内的注册项
        var cmpArray = Ext.getCmp(conId).removeAll();
        if (Ext.getCmp(toolbarId) != null) {
          var cmpArrayToolbar = Ext.EventManager.removeAll(toolbarId);
          cmpArray = Ext.Array.merge(cmpArray, cmpArrayToolbar);
        }
        //清空store
        for (var i = 0; i < cmpArray.length; i++) {
          if (cmpArray[i]) {
            if (cmpArray[i].store) {
              cmpArray[i].store.destroyStore();
              Ext.data.StoreManager.unregister(cmpArray[i].store);
            }
          }
        }
        cmpArray = null;
        Ext.ComponentManager.unregister(Ext.getCmp(conId));
        if (Ext.getCmp(toolbarId) != null) {
          Ext.ComponentManager.unregister(Ext.getCmp(toolbarId));
        }

        //清理模块下变量和方法
        var lineIndex = tabId.lastIndexOf("-"),
          moduleName = tabId.substring(2, lineIndex),
          endIndex = tabId.length,
          pointIndex = tabId.lastIndexOf("."),
          module = eval(moduleName);
        if (pointIndex != -1) {
          endIndex = pointIndex;
        }
        var childmoduleName = conId.substring(lineIndex + 1, endIndex);
        if (childmoduleName == "index") {
          if (module != null) {
            for (var prop in module) {
              if (!Ext.isObject(prop)) {
                try {
                  if (module[prop].id) {
                    cleanComponent(module[prop].id);
                  }
                }
                catch (err) {
                  module[prop] = null;
                }
              }
            }
            module = null;
          }
        } else {
          var childmodule = module[childmoduleName.slice(0, -5)];
          for (var prop in childmodule) {
            if (!Ext.isObject(prop)) {
              try {
                if (childmodule[prop].id) {
                  cleanComponent(childmodule[prop].id);
                }
              }
              catch (err) {
                childmodule[prop] = null;
              }
            }
          }
          childmodule = null;
        }
      },
      add:function(){
        hideNav();
      }
    };
  },
  constructor: function (config) {
    var me = this,
      cfg = Ext.apply({}, config);
    me.initListeners();
    me.callParent([cfg]);
  }
});
